<script lang="ts" setup>
import { onMounted, ref, nextTick, getCurrentInstance } from 'vue'
import { useDepartmentStore } from '../../store/department';
import department from '../../api/department';
import utils from '../../utils/utils';
import { useSettingStore } from '../../store/setting';
import { useAddDepartmentStore } from '../../store/addDepartment';
import { useDepartmentSelectStore } from '../../store/departmentSelect';
const addDepartmentStore = useAddDepartmentStore()
const departmentSelectStore = useDepartmentSelectStore()
const departmentStore = useDepartmentStore()
const settingStore = useSettingStore()
const tableRef = ref() // 获取表格实例引用

async function reflashData() {
    await department.getAllDepartmentList().then(res => {
        departmentStore.setDepartmentTable(res.data.data)
    }).catch(err => {
        console.log(err)
    }).finally(() => {
        departmentStore.changeLoading()
    })
    await department.getDepartmentSelect().then((res) => {
        departmentSelectStore.setDepartmentSelect(res.data.data);
        console.log(departmentSelectStore.departmentSelect);
    }).catch((err) => {
        console.log(err);
    });
}
async function editDepartment(id: string) {
    await department.getDepartmentById(id).then(res => {
        addDepartmentStore.setDepartment(res.data.data)
        addDepartmentStore.setIsOpen(true)
    }).catch(error => {
        console.error('获取部门详情失败:', error)
    })
}
function addDepartment(parentId: string) {
    addDepartmentStore.department.parentId = parentId
    departmentSelectStore.setDisabled(true)
    addDepartmentStore.setIsOpen(true)
}

async function deleteDepartment(id: string) {
    await department.deleteDepartmentById(id).then(() => {
        console.log('删除部门成功')
    }
    ).catch(error => {
        console.error('删除部门失败:', error)
    })
    reflashData();
}

onMounted(async () => {
    try {
        // 1. 加载原始数据
        const response = await department.getAllDepartmentList()
        console.log(response.data.data)

        // 2. 数据清洗
        const validData = response.data.data.filter(item =>
            item && typeof item === 'object' && 'id' in item
        )

        // 3. 更新store数据
        departmentStore.setDepartmentTable(validData)

        // 4. 等待双重DOM更新
        //await nextTick()

        // 5. 设置表格引用（确保使用最新DOM）
        if (!tableRef.value) {
            throw new Error('表格实例未正确挂载')
        }
        settingStore.setDepartmentRef(tableRef.value)

        // 6. 初始化展开状态（需在引用设置后执行）
        if (settingStore.isExpanded) {
            //await nextTick() // 额外等待确保引用生效
            settingStore.toggleAllExpansion()
        }

    } catch (error) {
        console.error('初始化流程错误:', error)

    }
})

</script>
<template>
    <el-table v-loading="departmentStore.loading" :data="departmentStore.departmentTable"
        style="width: 100%;margin-top: 1rem;" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id" :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: '600'
        }" :row-style="{ cursor: 'pointer' }" ref="tableRef">
        <!-- 部门名称列 -->
        <el-table-column label="部门名称" prop="deptName">
            <template #default="{ row }">
                <span :style="{
                    paddingLeft: `${row.level * 16}px`,
                    fontWeight: '600',
                    color: '#303133'
                }">
                    {{ row.deptName }}
                </span>
            </template>
        </el-table-column>

        <!-- 状态列 -->
        <el-table-column label="状态" prop="status" align="center" header-align="center" width="120">
            <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="dark"
                    :style="{ fontWeight: '500' }">
                    {{ scope.row.status === 1 ? '正常' : '停用' }}
                </el-tag>
            </template>
        </el-table-column>

        <!-- 负责人列 -->
        <el-table-column label="负责人" prop="realName" align="center" header-align="center" :show-overflow-tooltip="true">
            <template #default="scope">
                <span style="font-weight: 500">
                    {{ scope.row.realName || '-' }}
                </span>
            </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column label="创建时间" prop="createTime" align="center" header-align="center" width="180">
            <template #default="scope">
                <span style="color: #909399">
                    {{ utils.formatDate(scope.row.createTime) }}
                </span>
            </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" align="center" header-align="center" width="220">
            <template #default="scope">
                <div class="action-buttons">
                    <el-button type="primary" link size="small" @click="editDepartment(scope.row.id)">修改</el-button>
                    <el-button v-if="scope.row.id !== '5'" type="danger" link size="small"
                        @click="deleteDepartment(scope.row.id)">
                        删除
                    </el-button>
                    <el-button type="success" link size="small" @click="addDepartment(scope.row.id)">新增</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>
</template>

<style lang="scss" scoped>
// 表格整体样式调整
:deep(.el-table) {
    // 表头下边框颜色
    --el-table-border-color: #ebeef5;

    // 行悬停效果
    .el-table__body tr:hover>td {
        background-color: #f5f7fa !important;
    }

    // 单元格内边距调整
    .el-table__cell {
        padding: 12px 0;
    }
}

// 操作按钮容器
.action-buttons {
    display: flex;
    justify-content: center;
    gap: 8px;

    .el-button {
        margin: 0;
        font-weight: 500;
    }
}

// 树形缩进线样式
:deep(.el-table__row) {
    .el-table__cell {
        .cell {
            position: relative;

            // 添加树形连接线
            &::before {
                content: '';
                position: absolute;
                left: -8px;
                top: 50%;
                width: 10px;
                height: 1px;
                background: #dcdfe6;
            }
        }
    }

    // 隐藏首行的连接线
    &:first-child .el-table__cell .cell::before {
        display: none;
    }
}

.el-table__expand-icon {
    transition: transform 0.3s ease;
}

.el-table__expand-icon.expanded {
    transform: rotate(90deg);
}
</style>